﻿using System;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;

namespace CommonUtils
{
    /// <summary>
    /// ADO.NET for SqlServer
    /// </summary>
    public class DbSqlServer : DbBase
    {
        public static class ConnectStrings
        {
            public static string Get(string host, string user, string pwd, string database)
            => string.Format("Data Source={0};user={2};pwd={3};Initial Catalog={3};", host, user, pwd, database);

            public static string Get(string host, string database)
            => string.Format("Data Source={0};Integrated Security=True;Initial Catalog={1};", host, database);

            public static string GetDefault(string database = "test")
            {
                var connectString = Get(".", database);
                LogUtil.PrintInfo(connectString);
                return connectString;
            }

            public static string GetDefaultExpress(string database = "test")
            {
                var connectString = Get(".\\SQLEXPRESS", database);
                LogUtil.PrintInfo(connectString);
                return connectString;
            }
        }

        public DbSqlServer(string connectString)
        : base(connectString) { }

        public DbSqlServer(string host, string user, string password, string database)
        : this(string.Format("Data Source={0};User ID={1};pwd={2};Initial Catalog={3};", host, user, password, database)) { }

        protected override DbConnection GetConnection()
        => new SqlConnection(ConnectString);

        protected override DbParameter GetParameter(string key, object value)
        => new SqlParameter(key, value);

        [Obsolete]
        protected override DbDataAdapter GetDataAdapter(DbCommand cmd)
        => new SqlDataAdapter((SqlCommand)cmd);

        public override void BulkInsert(DataTable table)
        {
            if (table.TableName.IsNullOrEmpty())
                throw new ExceptionPlus("Empty TableName Not Allowed!");
            using (var bulk = new SqlBulkCopy(ConnectString))
            {
                bulk.BatchSize = table.Rows.Count;
                bulk.DestinationTableName = table.TableName;
                foreach (DataColumn column in table.Columns)
                    bulk.ColumnMappings.Add(column.ColumnName, column.ColumnName);
                bulk.WriteToServer(table);
            }
        }
    }
}
